import React, { Component, PropTypes } from 'react'
import { Link } from 'react-router'
import './../css/default-select.css'
import style from './OrderInfo.css'
import {ROOTPATH, myAjax, ROOTURL, myAjaxJson, ROOTURL_COMM, commonJsonFetch} from './../publicAPI/publicAPI'
import {tmToFormatTime} from './../publicAPI/commonF'

class OrderInfo extends Component {

	constructor (props, context) {
	    super(props, context)
	    var _rWapperHeigh = window.innerHeight;
	    this.state = {
	    	info: [],
	    	rHeight: _rWapperHeigh,
	    	filterBarbers: {},
	    	service: '',  //用于订单中对应服务类型
	    	filterShops: {},
	    	couponType: '', //优惠券类型
	    	isShowLoading: "block", //是否显示加载gif
	    	isReviewImg: 'none',
	    	reviewImg: '',
	    	commentInfo: {
	    		comm: 0,
	    		prof: 0,
	    		content: {
	    			contentInfo: '',
	    			img: []
	    		},
	    		response: {
	    			contentInfo: ''
	    		}
	    	} //评论信息
	     } // 初始化状态
	}

	componentDidMount() {
	    console.log("安装成功");

	    const _id = this.props.params.id
	    const self = this
		const newUrl = ROOTURL + '/contract/search.api';
		this.cId = this.props.params.id;

		//获取所有理发师
		this.getAllBabers()
		this.setState({filterShops: JSON.parse(sessionStorage.getItem("filterShops"))})
		//console.log(JSON.parse(sessionStorage.getItem("filterShops")))
		myAjaxJson(newUrl, 'POST', {
			where: {
				id: [["eq", _id]]
			}
		}, (data) => {
			console.log(data)
			this.setState({isShowLoading: "none"})
			self.getCustomer(data[0].customerId)
			self.setState({info: data})
			this.getServices(data[0].servTypeId)
			data[0].coupons&&data[0].coupons.length ? this.getCouponType(data[0].coupons[0].couponTypeId) : this.setState({couponType: "无"})
			if(data[0].stRate == "True" || data[0].stRate == true)
			 	this.getComment(_id);
		}, (data) => {
			this.setState({isShowLoading: "none"})
			alert("获取订单失败")
			console.log('failure'+ data)
		});
			
	}

	getAllBabers() {
		const newUrl= ROOTURL + 'servant/profile/search.api';
		var allBarbers = JSON.parse(sessionStorage.getItem("allBarbers"));
		if(allBarbers) {
			this.setState({filterBarbers: allBarbers})			
		} else {
			var allBarbers = {}
			myAjaxJson(newUrl, 'POST', {
				start: 0,
				limit: 1000
			}, (data) => {
				console.log(data)
				data.map((item, index) => {
					allBarbers[item.id] = {
						id: item.id,
						name: item.meta.name
					}
				})
				sessionStorage.setItem("allBarbers", JSON.stringify(allBarbers))
				this.setState({filterBarbers: allBarbers})
			}, (data) => {
				alert("获取理发师失败")
			})
		}
	}
	
	//获取所有服务类型
	getServices(id) {
		const newUrl= ROOTURL + 'serv/concrete/aggregated/search.api';

		myAjaxJson(newUrl, 'POST', {
			where: {
				id: [['eq', id]]
			}
		}, (data) => {
			//console.log(data)
			this.setState({service: data[0].dname})
		}, (data) => {
			alert("获取理发师失败")
		})

	}


	//获取订单中的客户
	getCustomer(id) {
		const newUrl= ROOTURL + 'customer/profile/search.api';
		const self = this
		myAjaxJson(newUrl, 'POST', {
			where: {
				id: [["eq", id]]
			}
		}, (data) => {
			//console.log(data)
			let customer = data[0]
			this.refs.customerPhone.innerHTML = customer ? customer.phone : ''
			this.refs.customerName.innerHTML = customer ? customer.dname : ''

		}, (data) => {
			console.log('failure', data)
		})
	}

	//获得优惠券信息
	getCouponType(id) {
		const newUrl= ROOTURL + 'coupon/type/search.api';

		myAjaxJson(newUrl, 'POST', {
			where: {
				id: [['eq', id]]
			}
		}, (data) => {
			console.log(data)
			this.setState({couponType: data[0].dname})
		}, (data) => {
			alert("获取理发师失败")
		})
	}

	//同意退款
	agreeRefund(id) {
		this.setState({isShowLoading: "block"})
		const newUrl = ROOTURL + 'contract/refund.api';
		let _data = {
			contractId: id,
			fullRefund : true
		}

		myAjax(newUrl, 'POST', _data, (data) => {
			console.log(1);
			console.log(data)
			this.sureAgreeRefund(id)
		}, (data) => {
			alert("订单"+_id+"同意退款失败")
			location.reload();
			console.log(data)
		});

	}

	//确认同意退款
	sureAgreeRefund(cId) {
		const newUrl = ROOTURL + 'contract/submit-refund.api';
		let _data = {
			contractId: cId,
		}
		myAjax(newUrl, 'POST', _data, (data) => {
			console.log(data)
			location.reload();
		}, (data) => {
			console.log(4);
			alert("订单"+cId+"同意退款失败")
			location.reload();
			console.log(data)
		});
	}

	//拒绝退款
	refuseRefund(id) {
		this.setState({isShowLoading: "block"})
		const newUrl = ROOTURL + 'contract/reject-refund.api';
		let _data = {
			contractId: id,
		}
		myAjax(newUrl, 'POST', _data, (data) => {
			console.log(data)
			location.reload();
		}, (data) => {
			alert("订单"+cId+"拒绝退款失败")
			location.reload();
			console.log(data)
		});
	}

	//获取评论信息
	getComment(id) {
		const newUrl = ROOTURL_COMM + 'rate/search.api';

		commonJsonFetch(newUrl, 'POST', {
				where: {
						id: [["eq", id]]
					}
				}, (data) => {
					console.log(data)
					this.setState({commentInfo: data[0]})
				}, (data) => {
					console.log(data)
				});
	}

	//回复信息
	responseCom(e) {
		const newUrl = ROOTURL_COMM + 'rate/edit.api';
		let responseVal = this.refs.respone.value,
			isDisplay = this.refs.displayCheck.checked;

		myAjaxJson(newUrl, 'POST', {
					id: this.cId,
					display: isDisplay,
					response: {
						contentInfo: responseVal
					}
				}, (data) => {
					alert("回复成功");
					location.reload();
				}, (data) => {
					alert("回复失败")
				});
	}
	//查看评论图片
	seeImg(e) {
		var imgSrc = e.target.src;
		this.setState({isReviewImg: 'block', reviewImg: imgSrc})
	}
	hideReview() {
		this.setState({isReviewImg: 'none'})
	}
	render() {
		const _state = {
			'-128': "未及时支付",
			'-96': "未及时到店服务",
			'0': "待支付",
			'16': "已支付",
			'-80': "申请退款",
			'-79': "已退款",
			'-64': "支付异常",
			'-78': "拒绝退款",
			'-112': "未及时到店服务"
		};
		const {selectClass} = this.props
		let info =this.state.info
		if (info.length > 0) {
			info = info[0]
		}

		let status = _state[info.stPayment];
		if(info.stServe) {
		 	status = "已服务";
		 	if(info.stRate) status = "已评价";

		}

		//评论信息dom
		let _commentInfo = this.state.commentInfo;

		return (
			<div className="right-wapper" style={{height: this.state.rHeight}}>
				<div className={style["review-wapper"]} style={{display: this.state.isReviewImg}} onClick={(e) => this.hideReview()}><img src={this.state.reviewImg ? this.state.reviewImg : require('./../imgs/loading.gif')} alt=""/></div>
				<div className="loading-wapper" style={{display: this.state.isShowLoading}}><img src={require('./../imgs/loading.gif')} alt=""/></div>
				<div className={style["orderInfo"]}>
					<div className={style["info-input"]}>
						<label>客户姓名：</label>
						<span ref="customerName"></span>
					</div>
					<div className={style["info-input"]}>
						<label>订单号：</label>
						<span>{info.id}</span>
					</div>
					<div className={style["info-input"]}>
						<label>客户手机：</label>
						<span ref="customerPhone"></span>
					</div>
					<div className={style["info-input"]}>
						<label>交易状态：</label>
						<span>{status}</span>
					</div>
					<div className={style["info-input"]}>
						<label>交易门店：</label>
						<span>{this.state.filterShops[info.shopId] ? this.state.filterShops[info.shopId].dname : ''}</span>
					</div>
					<div className={style["info-input"]}>
						<label>下单时间：</label>
						<span>{info.tmCreate ? tmToFormatTime(info.tmCreate) : ''}</span>
					</div>
					<div className={style["info-input"]}>
						<label>理发师：</label>
						<span>{this.state.filterBarbers[info.servantId] ? this.state.filterBarbers[info.servantId].name : ''}</span>
					</div>
					<div className={style["info-input"]}>
						<label>预约时间：</label>
						<span>{info.tmReserve ? tmToFormatTime(info.tmReserve) : ''}</span>
					</div>
					<div className={style["info-input"]}>
						<label>订单价格：</label>
						<span>{info.grossPay}</span>
					</div>
					
					<div className={style["info-input"]}>
						<label>服务时间：</label>
						<span>{info.tmServe ? tmToFormatTime(info.tmServe) : ''}</span>
					</div>
					<div className={style["info-input"]}>
						<label>实付金额：</label>
						<span>{info.netPay}</span>
					</div>
					<div className={style["info-input"]}>
						<label>服务类型：</label>
						<span>{this.state.service}</span>
					</div>
					<div className={style["info-input"]}>
						<label>使用优惠券：</label>
						<span>{this.state.couponType}</span>
					</div>

					{(info.stPayment===-80 || info.stPayment===-78 || info.stPayment===-79) &&  <div className={style["info-input"]}><label>退款理由：</label><span>{info.smeta &&info.smeta.Refund&&info.smeta.Refund.msgs[0]? info.smeta.Refund.msgs[0].m : "无"}</span></div>}
					<div className={style["info-input"]}>
					</div>
					<div className={style["commentInfo"]} style={{display: info.stRate ? "block" : "none"}}>
						<label>评论信息：</label>
						<div className={style["commentContent"]} >
							<div className={style["infoItem"]}>
								<label>服务态度：</label>
								<span>{_commentInfo.comm}</span>
							</div>
							<div className={style["infoItem"]}>
								<label>技术水平：</label>
								<span>{_commentInfo.prof}</span>
							</div>
							<div className={style["infoItem"]}>
								<label>客户评论内容：</label>
								<span>{_commentInfo.content.contentInfo}</span>
							</div>
							<div className={style["infoItem"]}>
								<label>客服回复内容：</label>
								<span>{_commentInfo.response ? _commentInfo.response.contentInfo : ''}</span>
							</div>
							<div className={style["infoItem"]}>
								<label style={{'verticalAlign': 'top'}}>评论图片：</label>
								{_commentInfo.content.img && _commentInfo.content.img.map((item, index) => <img src={ROOTURL_COMM+'/asset/images/get.api?hashed='+item} key={index} onClick={(e) => this.seeImg(e)}/>)}
								
							</div>
							<div className={style["infoItem"]}>
								<label>是否被屏蔽：</label>
								<span>{_commentInfo.display ? "否" : "是"}</span>
							</div>
						</div>
						<label>管理员回复评论：</label>
						<div className={style["commentContent"]}>
							<textarea ref="respone" placeholder="输入回复信息"></textarea>
							<div className={style["res-box"]}>
								<label>是否屏蔽该评论：</label><input type="checkbox" ref="displayCheck"/><br/><br/>
								<button className={"info-btn"} onClick={(e) => this.responseCom(e)}>回复</button>
							</div>
						</div>
						
					</div>
					<div>
						<Link to="/OrderM" className={style["info-btn"]}>返回</Link>
		    			<button className={"info-btn"}  style={{display: info.stPayment === -80 ? "inline-block" : "none"}} onClick={() => this.agreeRefund(info.id)}>退款</button>
						<button className={"info-btn"}  style={{display: info.stPayment === -80 ? "inline-block" : "none"}} onClick={() => this.refuseRefund(info.id)}>拒绝退款</button>
		    		</div>
				</div>
			</div>
		)
	}
}

export default OrderInfo
